# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.



from flask import Flask, session, redirect, url_for, escape, request
import pymysql
import json

app = Flask(__name__)
app.debug = True


@app.route("/")
def route_root():
    return  'hhu iot  root.'
@app.route("/login")
def route_login():
    return  'hhu iot -- login.'
@app.route("/info/<category>/<sub>")
def route_info(category, sub):
    a = request.args
    b = request.form
    c = request.query_string
    print(a)
    print(b)
    print(c)
    return ('info : %s ' % category ) +"("+sub+")"

@app.route("/sys/login")
def sysLogin():
    ps={}
    for p in request.args.keys():
        v = request.args[p]
        ps[p] = v
    args = request.args
    dbHelp.sqls["sys/login"] = "select * from T_UserInfo where nickName=%(userName)s and userPwd = %(pwd)s"
    res = dbHelp.dbExecute("sys/login" , ps , 0)
    resData = json.dumps(res,ensure_ascii=False)
    return  resData

@app.route("/sys/regist")
def sysRegist():
    nickName = request.args["userName"]
    pwd = request.args["pwd"]
    desc = request.args["desc"]
    ps = {
        "nickName": nickName ,
        "pwd":pwd,
        "desc":desc
    }
    dbHelp.sqls["sys/regist"] = "insert into T_UserInfo (nickName,userPwd,userDesc) values (%(nickName)s , %(pwd)s , %(desc)s )"
    res = dbHelp.dbExecute("sys/regist" , ps , 1)
    resData = json.dumps(res,ensure_ascii=False)

    return  resData

@app.route("/sys/query")
def stsQuery():
    sqlKey = request.args["sk"]
    executeFlag = request.args["e"]
    flag = 0
    if executeFlag=="1":
        flag = 1
    ps={}
    for p in request.args.keys():
        v = request.args[p]
        ps[p] = v
    res = dbHelp.dbExecute(sqlKey , ps , flag)
    resData = json.dumps(res,ensure_ascii=False)
    return  resData

class TDbHelp:
    def __init__(self):
        self.host = ""
        self.port = 0
        self.userName = ""
        self.pwd = ""
        self.db = ""

        self.sqls = {}
    def dbExecute ( self  , sqlKey , dictarams , flag):
        res={}
        try:
            sql = self.sqls[sqlKey]
            db = pymysql.connect(host= self.host, port=self.port, user=self.userName, passwd=self.pwd, db=self.db, charset="utf8")
            db.autocommit(True)
            # 使用cursor()方法获取操作游标
            cursor = db.cursor()
            if( dictarams != None):
                cursor.execute(sql , dictarams)
            else:
                cursor.execute(sql)
            if flag==0 and cursor.description!=None:
                cols = [desc[0] for desc in cursor.description ]
                res_json=[]
                results = cursor.fetchall()
                for  row in results:
                    res_json.append(
                        dict(zip(cols , row))
                    )
                res = res_json
            else:
                res={
                    "rowNum": cursor.rownumber ,
                    "rowCount": cursor.rowcount ,
                    "newId": cursor.lastrowid
                }
            cursor.close()
            db.close()
        except Exception as er:
            print(er)
        return  res
    def query(self , sqlKey , dictParams):
        res={}
        try:
            res = self.dbExecute(sqlKey , dictParams , 0);
        except Exception as er:
            print(er)
        return  res
    def execute(self , sqlKey , dictParams):
        res={}
        try:
            res = self.dbExecute(sqlKey , dictParams , 1);
        except Exception as er:
            print(er)
        return  res

dbHelp = TDbHelp()
dbHelp.host = "127.0.0.1"
dbHelp.port = 13306
dbHelp.userName="root"
dbHelp.pwd = "hhudbpwd"
dbHelp.db="db2023"

dbHelp.sqls["sys/login"] = "select * from T_UserInfo where nickName=%(userName)s and userPwd = %(pwd)s"
dbHelp.sqls["sys/regist"] = "insert into T_UserInfo (nickName,userPwd,userDesc) values (%(nickName)s , %(pwd)s , %(desc)s )"

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')
    app.run(host='127.0.0.1',port=5000)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
